package com.tuzki.zhuogui.data;

import java.io.IOException;
import java.io.Reader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.tuzki.zhuogui.core.Constants;

public class MybatisUtil {
	private static Log logger = LogFactory.getLog(MybatisUtil.class);
	
	private static SqlSessionFactory sessionFactory = null;
	
	public static SqlSession getSession() {
		if(sessionFactory == null){
			try {
				initMybatis();
			} catch (IOException e) {
				logger.error("mybatis init fail!", e);
			}
		}
		return sessionFactory.openSession();
		
	}

	private static void initMybatis() throws IOException {
		String resource = Constants.NAME_MYBATIS_CONFIG;
		Reader reader = Resources.getResourceAsReader(resource);
		sessionFactory = new SqlSessionFactoryBuilder().build(reader);
		logger.info("mybatis init success!");
	}

	public static void insert(String sqlId, Object object){
		getSession().insert(sqlId, object);
	}
}
